package com.hxx.widget.bar

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import com.hxx.widget.R


class AppToolBar @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), View.OnClickListener, AppToolBarMenuInflate {
    init {
        LayoutInflater.from(context).inflate(R.layout.widget_layout_toolbar, this, true)
        val a = context.obtainStyledAttributes(attrs, R.styleable.widget_AppToolBar)
        val finishActivity =
            a.getBoolean(R.styleable.widget_AppToolBar_widget_finish_activity, true)
        val title = a.getString(R.styleable.widget_AppToolBar_widget_toolbar_title)
        findViewById<AppCompatTextView>(R.id.widget_toolbar_title).apply {
            text = title
        }
        a.recycle()
        if (finishActivity) {
            findViewById<View>(R.id.widget_toolbar_navi).setOnClickListener {
                scanForActivity(context)?.finish()
            }
        } else {
            findViewById<View>(R.id.widget_toolbar_navi).setOnClickListener(this)
        }
    }

    private var defaultMenuLayoutId = R.layout.widget_layout_toolbar_menu_item

    interface MenuItemClickListener {
        fun onNavigationClick()
        fun onMenuClick(view: View, tag: Int)
    }

    private var menuListener: MenuItemClickListener? = null

    fun setMenuClickListener(listener: MenuItemClickListener) {
        this.menuListener = listener
    }

    fun addMenu(id: Int, icon: Int) {
        val menuView = createMenu(icon, id)
        menuView.setOnClickListener(this)
        addView(menuView)
    }

    private fun scanForActivity(context: Context?): Activity? {
        if (context == null) return null
        if (context is Activity) {
            return context
        } else if (context is ContextWrapper) {
            return scanForActivity(context.baseContext)
        }
        return null
    }

    override fun onClick(v: View?) {
        when(v){
            findViewById<View>(R.id.widget_toolbar_navi)->{

            }
            else ->{
                menuListener?.onMenuClick(v!!, v.tag as Int)
            }
        }
    }

    override fun createMenu(icon: Int, id: Int): View {
        return LayoutInflater.from(context).inflate(defaultMenuLayoutId, this, false).also {
            it as AppCompatImageView
            it.setTag(id)
            it.setImageResource(icon)
        }
    }
}